iT邦幫忙

2022 iThome 鐵人賽

DAY 5
0
Modern Web

React應用記錄誌系列 第 5

Day 05 實作練習useEffect( ) - Fetching Json data

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20220919/20139800bpbrYgg8mY.png

App.js

import React from "react";
import Data from "./components/Data";

const App = () => { 

  return (
    <div className="container">
       <Data />  
    </div>
  );
}

export default App;

Data.js

import React ,{useState,useEffect} from 'react'
import axios from 'axios'

const Data = () => {
    const [post,setPost] = useState({});
    const [id,setId] = useState();
    const [buttonId, setButtonId] = useState();

    const handleClick=()=>{
      setButtonId(id);
    }

    useEffect(()=>{
        axios.get(`https://jsonplaceholder.typicode.com/posts/${buttonId}`)
            .then(res=>{
                console.log(res)
                setPost(res.data)
            })
            .catch(err=>{
                console.log(err)
            })
    },[buttonId])

  return (
    <div className="app-box">
      <input 
      type="text"
      className='line-input' 
      placeholder='Enter Number...' 
      require 
      value={id}  
      onChange={e => setId(e.target.value)}  
      />
       <button 
       type="button"
       className='button-add' 
       onClick={handleClick}> Get Data </button>
       <div className='list-item'>{post.title}</div>       
    </div>
  )
}

export default Data


上一篇
Day04 React Hooks – useEffect
下一篇
Day06 React Context
系列文
React應用記錄誌31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言